<?php

class SimpleRecord {
	var $dir;
	var $count;
	var $pages;

	function SimpleRecord($dbDir) {
		if(substr($dbDir, -1) != '/')
			$dbDir .= '/';

		if(!is_dir($dbDir)) {
			@mkdir($dbDir);
			@chmod($dbDir, 0777);
		}

		$this->dir = dir($dbDir);
		$this->count = NULL;
	}

	function getLength() {
		if($this->count !== NULL)
			return $this->count;
		else
			$this->count = 0;

		while($entry = $this->dir->read()) {
			if($entry === FALSE)
				break;

			if($entry == '.' || substr($entry, 0, 2) != '0x')
				continue;

			++$this->count;
		}

		$this->dir->rewind();
		return $this->count;
	}

	function getChangeTimes($format = NULL) {
		$list = array();

		while($entry = $this->dir->read()) {
			if($entry === FALSE)
				break;

			if($entry == '.' || substr($entry, 0, 2) != '0x')
				continue;

			$list[hexdec(substr($entry, 2))] = filectime($this->dir->path.$entry);
		}

		$this->dir->rewind();

		for($i = 0; $format != NULL && $i < count($list); ++$i)
			$list[$i] = date($format, $list[$i]);

		ksort($list);
		return array_reverse($list, TRUE);
	}

	function get($i = NULL) {
		if($i === NULL)
			$i = $this->getLength() - 1;

		if($i < 0 || $i >= $this->getLength())
			return FALSE;

		if(isset($this->pages[$i]))
			return $this->pages[$i];

		return $this->pages[$i] = join('', file($this->dir->path.'0x'.dechex($i)));
	}

	function set($page) {
		if(trim($this->get()) == trim($page))
			return FALSE;

		$len = $this->getLength();
		$fp = @fopen($this->dir->path.'0x'.dechex($len), 'w');

		if(!$fp)
			return FALSE;

		if(!fwrite($fp, $page))
			return FALSE;

		fclose($fp);
		@chmod($this->dir->path.'0x'.dechex($len), 0777);

		$this->pages[$len] = $page;
		++$this->count;
	}
}

?>